package org.buptsse.study;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpDownLoader {
 private URL url;
 
 /**
  * 读取文本文件,返回字符串
  * @param urlStr
  * @return
  */
 public String download(String urlStr) {
  StringBuffer sb=new StringBuffer();
  String line=null;
  BufferedReader buffer=null;
  try {
   //创建一个url对象
   url=new URL(urlStr);
   //创建一个Http连接
   HttpURLConnection urlcon=(HttpURLConnection)url.openConnection();
   //使用IO读取数据
   buffer=new BufferedReader(new InputStreamReader(urlcon.getInputStream()));
   //循环
   while((line=buffer.readLine())!=null){
    sb.append(line);
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }finally{
   try {
    buffer.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
  return sb.toString();
 }
 
 /**
  * 读取文件，并保存起来
  * @param urlStr
  * @param path
  * @param fileName
  * @return -1:下载出错  0:成功    1: 文件已经存在
  */
 public int downFile(String urlStr,String path,String fileName){
  int result=-1;
  InputStream inputStream=null;
  FileUtils fileUtils=new FileUtils();
  System.out.println("urlString----->"+urlStr);
  try {
   if(fileUtils.isFileExist(path+fileName)){
    return 1;
   }else{
    inputStream=getInputStreamFromUrl(urlStr);
    File resultFile=fileUtils.write2SDFromInput(path, fileName, inputStream);
    if(resultFile==null){
     return -1;
    }
   }
   inputStream.close();
  } catch (IOException e) {
   System.out.println("download e----->"+e.toString());	  
   e.printStackTrace();
   return -1;
  }
  
  return 0;
 }
 /**
  * 根据url地址获取输入流
  * @param urlStr
  * @return
  * @throws IOException
  */
 public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
  InputStream inputStream = null;
  try{
  System.out.println("getInputStream----->");	 
  url=new URL(urlStr);
  System.out.println("getInputStream url----->"+url.toString());
  HttpURLConnection urlCon=(HttpURLConnection)url.openConnection();
  inputStream=urlCon.getInputStream();
  System.out.println("inputStream----->"+inputStream.toString());
  
 }
 catch(IOException e)
 {
	 System.out.println("getInputStream e----->"+e.toString());
 }
	 
	return inputStream;
 }
 
}
